/**
    Copyright (C) 2013 Guido Ludwig

	This file is part of JATT.
	http://code.google.com/p/jatt/

    JATT is free software. You can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.guidoludwig.jatt.google;

import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;

import org.json.JSONException;
import org.json.JSONObject;

import com.jgoodies.binding.list.SelectionInList;

/**
 * see also :
 * https://developers.google.com/image-search/v1/jsondevguide#using_json
 * 
 * @author Guido Ludwig
 * 
 */
public class GoogleImagesUtil {

	private final String searchString;
	private JSONObject jsonRoot;
	private List<GoogleImageInfo> imageInfos;

	public GoogleImagesUtil(String searchString) {
		this.searchString = searchString.replaceAll(" ", "%20");
		imageInfos = new ArrayList<GoogleImageInfo>();
	}

	public void search() {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			String myIP = addr.getHostAddress();
			URL url = new URL(
					"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&userip="
							+ myIP + "&q=" + searchString);
			URLConnection connection = url.openConnection();

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			jsonRoot = new JSONObject(builder.toString());

			int count = getImagesCount();
			for (int i = 0; i < count; i++) {
				GoogleImageInfo info = new GoogleImageInfo(jsonRoot
						.getJSONObject("responseData").getJSONArray("results")
						.getJSONObject(i));
				imageInfos.add(info);

			}

		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Failure",
					JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}

	}

	public int getImagesCount() throws JSONException {
		return jsonRoot.getJSONObject("responseData").getJSONArray("results")
				.length();
	}

	public void showImage(int index) throws IOException {

		GoogleImageInfo info = imageInfos.get(index);
		JOptionPane
				.showMessageDialog(null,
						info.getWidth() + "x" + info.getHeight() + "px",
						"Image Search powered by Google",
						JOptionPane.INFORMATION_MESSAGE,
						new ImageIcon(info.getThumb()));

	}

	public void showAll() {
		@SuppressWarnings("unchecked")
		JList<GoogleImageInfo> list = new JList<GoogleImageInfo>(
				new SelectionInList<GoogleImageInfo>(imageInfos));
		list.setCellRenderer(new GoogleImageInfoListCellRenderer());
		JFrame frame = new JFrame();
		frame.setPreferredSize(new Dimension(500, 500));
		frame.add(new JScrollPane(list));
		frame.pack();
		frame.setVisible(true);

	}

	public static void main(String[] args) {
		GoogleImagesUtil giu = new GoogleImagesUtil(
				"Afghan Whigs 1996 Black Love");
		try {
			giu.search();
			giu.showAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
